from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QLabel, QLineEdit, QTextEdit,
    QDateTimeEdit, QPushButton, QHBoxLayout, QMessageBox
)
from PyQt5.QtCore import QDateTime
from datetime import datetime

from core.schedule_manager import ScheduleService
from database.db_session import get_db


class ScheduleDialog(QDialog):
    def __init__(self, user_id, schedule=None):
        super().__init__()
        self.setWindowTitle("编辑日程" if schedule else "添加日程")
        icon = QIcon("E:/pythonwork/personal_schedule_system/rsc/icon.jpg")
        self.setWindowIcon(icon)
        self.user_id = user_id
        self.schedule = schedule
        self.resize(400, 300)
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        self.title_input = QLineEdit()
        self.title_input.setPlaceholderText("标题")
        layout.addWidget(QLabel("日程标题"))
        layout.addWidget(self.title_input)

        # 默认为当前时间
        self.start_time_input = QDateTimeEdit(QDateTime.currentDateTime())
        self.start_time_input.setCalendarPopup(True)
        layout.addWidget(QLabel("开始时间"))
        layout.addWidget(self.start_time_input)

        self.end_time_input = QDateTimeEdit(QDateTime.currentDateTime())
        self.end_time_input.setCalendarPopup(True)
        layout.addWidget(QLabel("结束时间(可选)"))
        layout.addWidget(self.end_time_input)

        self.reminder_time_input = QDateTimeEdit(QDateTime.currentDateTime())
        self.reminder_time_input.setCalendarPopup(True)
        layout.addWidget(QLabel("提醒时间（可选）"))
        layout.addWidget(self.reminder_time_input)

        self.notes_input = QTextEdit()
        layout.addWidget(QLabel("备注"))
        layout.addWidget(self.notes_input)

        # 如果是编辑模式，预填充数据
        if self.schedule:
            self.fill_form(self.schedule)

        btn_layout = QHBoxLayout()
        self.save_btn = QPushButton("保存")
        self.save_btn.setObjectName("save_btn")
        self.save_btn.clicked.connect(self.save_schedule)
        self.save_btn.setShortcut("Return")

        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.setObjectName("cancel_btn")
        self.cancel_btn.clicked.connect(self.reject)

        btn_layout.addWidget(self.save_btn)
        btn_layout.addWidget(self.cancel_btn)

        layout.addLayout(btn_layout)
        self.setLayout(layout)

        self.setStyleSheet("""
            /* 主窗口 */
            QDialog {
                background-color: qlineargradient(
                    spread:pad, x1:0, y1:0, x2:1, y2:1,
                    stop:0 #e0f7fa, stop:1 #ffffff
                );
                border-radius: 12px;
                border: 1px solid rgba(255, 255, 255, 0.3);
            }


            /* 按钮样式 */
            QPushButton {
                font-family: 'Microsoft YaHei';
                font-size: 8pt;
                font-weight: medium;
                border-radius: 8px;
                padding: 0 25px;
                min-width: 80px;
                height: 40px;
                border: none;
            }

            QPushButton#save_btn {
                background-color: #4a90e2;
                color: white;
            }

            QPushButton#save_btn:hover {
                background-color: #3a7bc8;
            }

            QPushButton#save_btn:pressed {
                background-color: #2a6cb2;
            }

            QPushButton#cancel_btn {
                background-color: #f5f5f5;
                color: #666666;
                border: 1px solid #e0e0e0;
            }

            QPushButton#cancel_btn:hover {
                background-color: #eeeeee;
            }

            QPushButton#cancel_btn:pressed {
                background-color: #e0e0e0;
            }
        """)

    def fill_form(self, s):
        self.title_input.setText(s.title)
        self.start_time_input.setDateTime(QDateTime(s.start_time))
        if s.end_time:
            self.end_time_input.setDateTime(QDateTime(s.end_time))
        if s.reminder_at:
            self.reminder_time_input.setDateTime(QDateTime(s.reminder_at))
        self.notes_input.setPlainText(s.notes or "")

    def save_schedule(self):
        title = self.title_input.text().strip()
        if not title:
            QMessageBox.warning(self, "提示", "标题不能为空")
            return

        start_time = self.start_time_input.dateTime().toPyDateTime()
        if not start_time:
            QMessageBox.warning(self, "提示", "开始时间不能为空")
            return

        # 获取可选时间字段
        end_time_dt = self.end_time_input.dateTime().toPyDateTime()
        reminder_dt = self.reminder_time_input.dateTime().toPyDateTime()

        now = datetime.now()
        # 如果结束时间早于开始时间，提示错误
        if end_time_dt < start_time or end_time_dt == now:
            end_time = None  # 可省略
        else:
            end_time = end_time_dt

        # 如果提醒时间早于当前时间，视为未设置
        reminder_at = reminder_dt if reminder_dt >= now else None

        notes = self.notes_input.toPlainText().strip()

        data = {
            "title": title,
            "start_time": start_time,
            "end_time": end_time,
            "reminder_at": reminder_at,
            "notes": notes
        }

        try:
            db = next(get_db())
            if self.schedule:  # 修改
                ScheduleService.update_schedule(db, self.schedule.id, **data)
                QMessageBox.information(self, "成功", "日程修改成功")
            else:  # 新增
                ScheduleService.add_schedule(db, user_id=self.user_id, **data)
                QMessageBox.information(self, "成功", "日程添加成功")
        finally:
            db.close()
        self.accept()